package com.ieslab.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Servlet Filter implementation class BaseFilter
 */
@WebFilter(asyncSupported = true, description = "解决GET/POST编码问题", dispatcherTypes = DispatcherType.REQUEST, displayName = "encoding", filterName = "encoding of GET|POST", initParams = {
		@WebInitParam(name = "filter's name", value = "encodingFilter"),
		@WebInitParam(name = "ignore_uri", value = "/first/test.do,/filter/test.do") }, urlPatterns = { "/*" })
public class BaseFilter implements Filter {
	private static final String IGNORE_URI = "ignore_uri";
	private static final String URI_SEPARATOR = ",";
	private Set<String> ignoreUris = new HashSet<String>();

	/**
	 * Default constructor. 
	 */
	public BaseFilter() {
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		Enumeration<String> parameters = fConfig.getInitParameterNames();
		System.out.println("-----FilterConfig------");
		while (parameters.hasMoreElements()) {
			String parameter = parameters.nextElement();
			System.out.println(parameter + "=" + fConfig.getInitParameter(parameter));
		}
		System.out.println("---------FilterConfig----------");
		String originalUris = fConfig.getInitParameter(IGNORE_URI);
		if (originalUris != null) {
			String[] uris = originalUris.split(URI_SEPARATOR);
			for (String uri : uris) {
				this.ignoreUris.add(uri);
			}
		}
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uri = httpRequest.getRequestURI();
		if (!ignoreUris.contains(uri)) {
			if (httpRequest.getMethod().equals("POST")) {
				httpRequest = new EncodingRequest(httpRequest);
			} else {
				httpRequest.setCharacterEncoding("UTF-8");
			}
		}
		chain.doFilter(httpRequest, response);
		System.out.println("----------filter end------------");
	}

	private static final class EncodingRequest extends HttpServletRequestWrapper {
		public EncodingRequest(HttpServletRequest request) {
			super(request);
		}

		/** 
		 * 对请求参数进行编码
		 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) 
		 */
		@Override
		public String getParameter(String name) {
			String value = super.getParameter(name); // gkq:
			String encoding = super.getCharacterEncoding(); // gkq:请求体的编码[Get方法没有请求体，所以编码为null]
			System.out.println("encoding=" + encoding);
			System.out.println("{" + name + "=" + value + "}");
			if (value != null) {
				try {
					value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				}
			}
			return value;
		}
	}
}
